<?php declare(strict_types=1);


namespace App\Api\V2\Controller\Merchant;

use App\Api\Controllers\BaseController;
use App\Exceptions\BizException;
use App\Models\Goods;
use App\Models\MerchantStore;
use App\Models\Store;
use App\Models\StoreGoods;
use App\Models\StoreGoodsCate;
use App\Traits\ResponseTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class GoodsController extends BaseController
{
    use ResponseTrait;


    protected function vaild(Request $request): array
    {
        $store_id = $request->input("store_id");
        if (empty($store_id)) {
            throw new BizException("门店ID不能为空");
        }
        $user = $this->parseToken();
        $merchant_id = (int)$user->merchant_id;
        $merStore = MerchantStore::query()->where("merchant_id", $merchant_id)
            ->where("store_id", $store_id)
            ->first();
        if (empty($merStore)) {
            throw new BizException("当前商户没有绑定该店铺");
        }
        $store = Store::query()->where([
            "store_id" => $store_id,
        ])->first();
        if (empty($store)) {
            throw new BizException("门店不存在");
        }
        return [$store];
    }


    public function goodsDetails(Request $request)
    {
        $storeId = $request->input("store_id");
        $goodCode = $request->input("goods_code");
        $storeGoods = StoreGoods::query()->where("store_id", $storeId)->where("code", $goodCode)->first();

        if (!$storeGoods) {
            $res = $this->post('http://item.td365.com.cn/GetGoodsInfo.ashx?model=nossl', ['no' => '86000001', 'product' => 'yxposv10', 'itemcode' => $goodCode]);

            $storeGoods = [
                'store_id' => $storeId,
                'title' => $res['Name'],
                'num' => 99999,
                'code' => $res['Code'],
                'price' => $res['Price'],
                'sort' => 1,
                'status' => 2,
                'store_goods_cate_id' => 0
            ];
            StoreGoods::query()->insert($storeGoods);
        } else {
            $storeGoods = $storeGoods->toArray();
        }
        return $this->successResponse("ok", ["data" => $storeGoods]);
    }

    public function cateList ()
    {
        $cateList = StoreGoodsCate::query()->get();
        return $this->successResponse("ok", ["data" => $cateList]);
    }

    public function editGoods(Request $request)
    {
        $storeId = $request->input("store_id");
        $goodCode = $request->input("goods_code");
        $goodNum = $request->input("goods_num");
        $goodPrice = $request->input("goods_price");
        $goodTitle = $request->input("goods_title");
        $cateId = $request->input("cate_id");
        $res = StoreGoods::query()->where("store_id", $storeId)->where("code", $goodCode)->update([
            'title' => $goodTitle,
            'num' => $goodNum,
            'price' => $goodPrice,
            'store_goods_cate_id' => $cateId
        ]);
        if ($res) {
            return $this->successResponse("ok", []);
        } else {
            return $this->errorResponse('操作失败');
        }
    }

    public function post ($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url); //设置选项，包括URL
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //绕过ssl验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen(json_encode($data))
            )
        );

        $output = curl_exec($ch); //执行并获取HTML文档内容

        curl_close($ch); //释放curl句柄
        $output = json_decode($output, true);
        return $output;

    }

    public function goodsList(Request $request): string
    {
        try {
            list($store) = $this->vaild($request);
            $where = [
                "page" => (int)$request->input("page", 1),
                "pagesize" => (int)$request->input("pagesize", 10)
            ];
            $storeGoods = StoreGoods::query()->where("store_id", $store->store_id)
                ->with("cate")
                ->paginate($where["pagesize"], ["*"], "page", $where["page"]);
            return $this->successResponse("ok", ["data" => [
                "total" => $storeGoods->total(),
                "list" => $storeGoods->items(),
                "page" => $storeGoods->currentPage()
            ]]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    public function goodsDiff(Request $request): string
    {
        try {
            list($store) = $this->vaild($request);

            $storeGoods = StoreGoods::query()->where("store_id", $store->store_id)->get()->toArray();
            $storeGoods = array_combine(array_column($storeGoods, "code"), $storeGoods);
            $baseGoods = StoreGoods::query()->where("store_id", "-1")->get()->toArray();
            $diff = [];
            foreach ($baseGoods as $baseGood) {
                if (!isset($storeGoods[$baseGood["code"]])) {
                    $diff[] = $baseGood;
                }
            }
            $cateId = array_column($diff, "store_goods_cate_id");
            $cate = StoreGoodsCate::query()->whereIn("id", $cateId)->get()->toArray();
            $cateFmt = array_combine(array_column($cate, "id"), $cate);
            foreach ($diff as $k => $item) {
                $item["cate"] = null;
                if (isset($cateFmt[$item["store_goods_cate_id"]])) {
                    $item["cate"] = $cateFmt[$item["store_goods_cate_id"]];
                }
                $diff[$k] = $item;
            }
            //$diff 差异数据归类
            $diffCate = [];
            foreach ($diff as $item) {
                $cateName = $item["cate"]["title"] ?? "";
                $diffCate[$item["store_goods_cate_id"]]["cate_id"] = $item["store_goods_cate_id"];
                $diffCate[$item["store_goods_cate_id"]]["cateName"] = $cateName;
                $diffCate[$item["store_goods_cate_id"]]["goods_id"][] = $item["id"];
                $diffCate[$item["store_goods_cate_id"]]["goods"][] = $item;
            }
            $diffCateFmt = [];
            foreach ($diffCate as $item) {
                $diffCateFmt[] = $item;
            }
            return $this->successResponse("ok", ["data" => $diffCateFmt]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    public function goodsSync(Request $request): string
    {
        try {
            list($store) = $this->vaild($request);
            $goods_ids = $request->input("goods_id", []);
            if (empty($goods_ids)) {
                throw new BizException("商品ID不存在");
            }
            $goods_ids = array_unique($goods_ids);
            $storeGoods = StoreGoods::query()->whereIn("id", $goods_ids)->where("store_id", $store->store_id)->get()->toArray();
            $storeGoods = array_combine(array_column($storeGoods, "code"), $storeGoods);
            $baseGoods = StoreGoods::query()->whereIn("id", $goods_ids)->where("store_id", "-1")->get()->toArray();
            $created = [];
            foreach ($baseGoods as $baseGood) {
                if (!isset($storeGoods[$baseGood["code"]])) {
                    $created[] = [
                        "store_id" => $store->store_id,
                        "title" => $baseGood["title"],
                        "img" => $baseGood["img"],
                        "num" => $baseGood["num"],
                        "code" => $baseGood["code"],
                        "price" => $baseGood["price"],
                        "status" => 2,
                        "sort" => $baseGood["sort"],
                        "create_at" => date("Y-m-d H:i:s", time()),
                        "store_goods_cate_id" => $baseGood["store_goods_cate_id"]
                    ];
                }
            }
            if (!empty($created)) {
                if (!StoreGoods::query()->insert($created)) {
                    throw new BizException("同步失败");
                }
            }
            return $this->successResponse("ok", true);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    public function editGoodsPrice(Request $request): string
    {
        try {
            $data = $request->all();
            $validator = Validator::make($data, [
                "goods_id" => ["required", "min:0"],
                "price" => ["required"],
                "store_id" => ["required"]
            ]);
            if ($validator->fails()) {
                throw new BizException($validator->errors()->first());
            }
            list($store) = $this->vaild($request);
            $storeGoods = StoreGoods::query()->where("id", $data["goods_id"])->where("store_id", $store->store_id)->first();
            if (empty($storeGoods)) {
                throw new BizException("商品不存在");
            }
            $storeGoods->price = $data["price"];

            if (!$storeGoods->save()) {
                throw new BizException("更新失败");
            }
            return $this->successResponse("ok", true);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }


}